import { $ajax, $uploadFile } from './utils/network';
import { setToken, setUserInfo } from './utils/util';
import { wxMpLogin } from './api/login'

// app.ts
App<IAppOption>({
  globalData: {},
  onLaunch() {
    wx.$ajax = $ajax;
    wx.$uploadFile = $uploadFile;

    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: res => {
        console.log(res.code)
        // 发送 res.code 到后台换取 openId, sessionKey, unionId

        // 获取小程序appid
        const appId = wx.getAccountInfoSync().miniProgram.appId;
        wxMpLogin({
          appid: appId,
          code: res.code,
          device: 5
        }).then(res => {
          console.log(res)
          if (!res || !res.ok) return false

          if (!res.data.token) {
            return wx.showModal({
              title: '提示',
              content: '登录失败，请稍后重试',
              showCancel: false
            })
          }

          console.log(`[res.data.token]:`, res.data)

          setToken(res.data.token)
          setUserInfo(res.data)

          console.log(res)
        })
      },
    })
  },
})
